package cn.myframe;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.jms.annotation.JmsListener;

import javax.jms.*;

/*******************
 *@Describe 消息队列接收
 *@author 封神梦
 *@Time 2022/8/2
 *@Company
 ****************/
public class ActiveMQReciver {
    public static void main(String[] args) {
        try {
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");

            //2.创建连接
            Connection connection = connectionFactory.createConnection();

            //3.启动连接
            connection.start();

            //4.获取session(会话对象)
    /*
    arg0 是否启用事务
    arg1 消息的确认方式 自动确认
     */
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //5.创建一个队列对象,名称
            Queue firstQueue = session.createQueue("firstQueue");


            //6.创建消息消费者对象
            MessageConsumer consumer = session.createConsumer(firstQueue);

            //7.设置监听
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        System.out.println("提取的消息是" + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            //8.等待键盘输入
            //目的是为了让程序停止来看效果
            System.in.read();


            //9.关闭资源
            consumer.close();
            session.close();
            connection.close();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }

    //接收消息--设置消费者监听的目的地（队列），如果监听到队列中有消息，通过方法的形参表示接收到的消息
    @JmsListener(destination = "${queue-boot-name}")
    public void receiveMsg(TextMessage textMessage) throws JMSException {
        System.out.println("p2p模式下的消费者接收到队列中的消息："+textMessage.getText());
    }
}
